package com.hzeport.bgs22emduty.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzeport.bgs22emduty.config.SystemConfig;
import com.hzeport.bgs22emduty.config.login.LoginCompoentService;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.dto.ScreenDutyMessageDTO;
import com.hzeport.bgs22emduty.dto.WebSocketSendInfoDTO;
import com.hzeport.bgs22emduty.dto.messgeDistribute.ScreenMessageDistributeHideDTO;
import com.hzeport.bgs22emduty.entity.*;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
import com.hzeport.bgs22emduty.outbound.BaseDeptInfoRepository;
import com.hzeport.bgs22emduty.outbound.BasePersonInfoRepository;
import com.hzeport.bgs22emduty.outbound.ScreenDutyMapsRepository;
import com.hzeport.bgs22emduty.outbound.ScreenDutyMessageRepository;
import com.hzeport.bgs22emduty.service.*;
import com.hzeport.bgs22emduty.util.WordUtils;
import com.hzeport.bgs22emduty.vo.ls.ScreenDutyMessageSaveVO;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import com.hzeport.bgs22emduty.common.utils.IpUtils;
import com.hzeport.bgs22emduty.common.base.BaseServiceImpl;
import com.hzeport.bgs22emduty.outbound.db.ScreenDutyMessageRepositoryImpl;
import freemarker.template.TemplateException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * ${comments}
 *
 * @author code generator
 * @date 2023-02-14 09:39:44
 */
@Service
@Slf4j
public class ScreenDutyMessageServiceImpl extends BaseServiceImpl<ScreenDutyMessageRepositoryImpl, ScreenDutyMessage> implements ScreenDutyMessageService {

    @Resource
    private ScreenDutyMessageRepository screenDutyMessageRepository;

    @Resource
    private LoginCompoentService loginCompoentService;

    @Resource
    private SystemConfig systemConfig;

    @Resource
    private BasePersonInfoRepository basePersonInfoRepository;
    @Resource
    private BaseDeptInfoService baseDeptInfoService;
    @Resource
    private ParamDictionaryService paramDictionaryService;
    @Resource
    private BaseDeptInfoRepository baseDeptInfoRepository;

    @Resource
    private WebSocketSendInfoServer webSocketSendInfoServer;
    @Resource
    private ScreenDutyMapsRepository screenDutyMapsRepository;
    @Resource
    private SecurityLogService securityLogService;

    @Override
    public Page<ScreenDutyMessage>  page(ScreenDutyMessageDTO dto) {
        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        LambdaQueryWrapper<ScreenDutyMessage> queryWrapper = new LambdaQueryWrapper<ScreenDutyMessage>();
//        if (!userInfoDetailVO.getRole().contains("ZGGLY")) {
            queryWrapper.eq(StringUtils.isNotBlank(userInfoDetailVO.getCustomscode()), ScreenDutyMessage::getCustomId, userInfoDetailVO.getCustomscode());
//        }else {
//            queryWrapper.apply( "CUSTOM_ID = SEND_DEPT_ID");
//        }
        if (!CollectionUtils.isEmpty(dto.getDates())&&StringUtils.isNotBlank(dto.getDates().get(0))){
            LocalDateTime startLocalDateTime = LocalDate.parse(dto.getDates().get(0), DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay();
            queryWrapper.ge(ScreenDutyMessage::getCreateTime,startLocalDateTime);
        }
        if (!CollectionUtils.isEmpty(dto.getDates())&&StringUtils.isNotBlank(dto.getDates().get(1))){
            LocalDateTime endLocalDateTime = LocalDate.parse(dto.getDates().get(1), DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay().plusDays(1);
            queryWrapper.le(ScreenDutyMessage::getCreateTime,endLocalDateTime);
        }
        if (StringUtils.isNotBlank(dto.getCustomId())){
            queryWrapper.eq(ScreenDutyMessage::getSendCustomID,dto.getCustomId());
        }
        if (StringUtils.isNotBlank(dto.getTitle())){
            queryWrapper.like(ScreenDutyMessage::getTitle,dto.getTitle());
        }
        queryWrapper.orderByDesc(ScreenDutyMessage::getCreateTime);
        Page<ScreenDutyMessage> page = screenDutyMessageRepository.page(new Page<>(dto.getPageNum(), dto.getPageSize()), queryWrapper);
        page.getRecords().stream().forEach(i->{
            if (i!=null&&!StringUtils.isEmpty(i.getTagCode())){
                i.setTagCode(paramDictionaryService.getNameWithModuleAndParamCode("XXLX",i.getTagCode()));
            }
            if (!StringUtils.isEmpty(i.getSendDeptID())) {
                BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(i.getSendDeptID());
                if (baseDeptInfo!=null){
                    i.setCustomName(baseDeptInfo.getCustomName());
                }
            }
        });
        return page;
    }


    @Override
    public BaseResult savels( ScreenDutyMessageSaveVO screenDutyMessageSaveVO, HttpServletRequest request ) {
        if (StringUtils.isEmpty(screenDutyMessageSaveVO.getTitle())){
            return BaseResult.failed("消息标题不能不能为空");
        }
        ScreenDutyMessage screenDutyMessage = new ScreenDutyMessage();
        BeanUtils.copyProperties(screenDutyMessageSaveVO,screenDutyMessage);
        screenDutyMessage.setStatus("0");
        if (!StringUtils.isEmpty(screenDutyMessageSaveVO.getPersonNo())){
            screenDutyMessage.setCreatePerson(screenDutyMessageSaveVO.getPersonNo());
            List<BasePersonInfo> basePersonInfo=basePersonInfoRepository.list(new LambdaQueryWrapper<BasePersonInfo>()
                    .eq(BasePersonInfo::getUserno,screenDutyMessageSaveVO.getPersonNo()));
            if (basePersonInfo!=null){
                BasePersonInfo tempBasePerson=basePersonInfo.stream().filter(i->"0".equals(i.getSideLine()))
                        .findAny().orElse(null);
                if (tempBasePerson==null){
                    tempBasePerson=basePersonInfo.get(0);
                }
                String baseDeptId=baseDeptInfoService.getCustomIdByDeptId(tempBasePerson.getDeptId());
                BaseDeptInfo baseDeptInfo=baseDeptInfoRepository.getById(baseDeptId);
//                BaseDeptInfo baseDeptInfo=basePersonInfoRepository.getById()
                screenDutyMessage.setCustomId(baseDeptInfo.getId());
                screenDutyMessage.setCustomName(baseDeptInfo.getDeptName());
            }
        }
        if(StringUtils.isEmpty(screenDutyMessage.getId())){
            screenDutyMessage.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            screenDutyMessage.setCreateTime(LocalDateTime.now());
            screenDutyMessage.setUpdateTime(LocalDateTime.now());
            screenDutyMessageRepository.save(screenDutyMessage);
        }else {
            screenDutyMessage.setUpdateTime(LocalDateTime.now());
            screenDutyMessage.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            screenDutyMessageRepository.updateById(screenDutyMessage);
        }
        SecurityLog operateLog = new SecurityLog();
        operateLog.setCreateBy(screenDutyMessageSaveVO.getCreatePerson());
        operateLog.setCreateTime(LocalDateTime.now());
        operateLog.setIpAddress( IpUtils.getIpAddr(request));
        operateLog.setSDescription( JSON.toJSONString( screenDutyMessageSaveVO ) );
        operateLog.setSModule("ZBXXLS");
        operateLog.setSTitle("ZBBC");
        securityLogService.save(operateLog);
        return BaseResult.ok(screenDutyMessage,"保存成功");
    }

    @Override
    public BaseResult exportDoc(String id, HttpServletResponse response) throws IOException, TemplateException {
        ScreenDutyMessage screenDutyMessage=screenDutyMessageRepository.getById(id);
        if (screenDutyMessage==null){
            log.error("id未取得数据",id);
            return BaseResult.ok("id未取得数据");
        }
        HashMap<String, Object> dataMap = new HashMap();
        String templatePath = systemConfig.getTemplatePath();
                dataMap.put("title", screenDutyMessage.getTitle());
        dataMap.put("content", screenDutyMessage.getMainBody()!=null?screenDutyMessage.getMainBody():"");
        dataMap.put("time", screenDutyMessage.getCreateTime().getYear()+"年"
                +screenDutyMessage.getCreateTime().getMonth().getValue()+"月"
                +screenDutyMessage.getCreateTime().getDayOfMonth()+"日"
        );
        String templateName = "国务院联防联控机制组督导工作类信息模板.ftl";
        response.setContentType("application/octet-stream;chartset=utf-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("值班信息.doc", "UTF-8"));
        WordUtils.generateWord(dataMap, templateName,templatePath,response);
        return null;
    }

    @Override
    public Object update(ScreenDutyMessage screenDutyMessage) {
        ScreenDutyMessage screenDutyMessage1 = new ScreenDutyMessage();
        BeanUtils.copyProperties(screenDutyMessage,screenDutyMessage1);
        if(StringUtils.isEmpty(screenDutyMessage.getMainBody())){
            screenDutyMessage1.setMainBody("");
        }
        if (StringUtils.isEmpty(screenDutyMessage.getId())){
            ScreenDutyMessage byId = screenDutyMessageRepository.getById(screenDutyMessage.getId());
            if (byId != null){
                screenDutyMessage1.setRecVersion(byId.getRecVersion());
            }
        }
        screenDutyMessageRepository.updateById(screenDutyMessage1);
        return screenDutyMessage1;
    }

    @Override
    public BaseResult escalation(ScreenDutyMessageSaveVO screenDutyMessageSaveVO, HttpServletRequest request) {
        if (StringUtils.isEmpty(screenDutyMessageSaveVO.getTitle())){
            return BaseResult.failed("消息标题不能不能为空");
        }
        ScreenDutyMessage screenDutyMessage = new ScreenDutyMessage();
        BeanUtils.copyProperties(screenDutyMessageSaveVO,screenDutyMessage);
        screenDutyMessage.setStatus("0");
        if (!StringUtils.isEmpty(screenDutyMessageSaveVO.getPersonNo())){
            screenDutyMessage.setCreatePerson(screenDutyMessageSaveVO.getPersonNo());
            List<BasePersonInfo> basePersonInfo=basePersonInfoRepository.list(new LambdaQueryWrapper<BasePersonInfo>()
                    .eq(BasePersonInfo::getUserno,screenDutyMessageSaveVO.getPersonNo()));
            if (basePersonInfo!=null){
                BasePersonInfo tempBasePerson=basePersonInfo.stream().filter(i->"0".equals(i.getSideLine()))
                        .findAny().orElse(null);
                if (tempBasePerson==null){
                    tempBasePerson=basePersonInfo.get(0);
                }
                String baseDeptId=baseDeptInfoService.getCustomIdByDeptId(tempBasePerson.getDeptId());
                BaseDeptInfo baseDeptInfo=baseDeptInfoRepository.getById(baseDeptId);
//                BaseDeptInfo baseDeptInfo=basePersonInfoRepository.getById()
                screenDutyMessage.setCustomId(baseDeptInfo.getId());
                screenDutyMessage.setCustomName(baseDeptInfo.getDeptName());
            }
        }
        BaseDeptInfo hzDeptInfo = baseDeptInfoRepository.getOne(new LambdaQueryWrapper<BaseDeptInfo>()
                .eq(BaseDeptInfo::getDeptName, systemConfig.getZsCustomName()));
        if(StringUtils.isEmpty(screenDutyMessage.getId())){
            screenDutyMessage.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            screenDutyMessage.setCreateTime(LocalDateTime.now());
            screenDutyMessage.setUpdateTime(LocalDateTime.now());
            if (screenDutyMessage.getCustomId()==null) {
                screenDutyMessage.setCustomId(hzDeptInfo.getId());
                screenDutyMessage.setCustomName(hzDeptInfo.getDeptName());
            }
            screenDutyMessageRepository.save(screenDutyMessage);
        }else {
            ScreenDutyMessage byId = screenDutyMessageRepository.getById(screenDutyMessage.getId());
            screenDutyMessage.setUpdateTime(LocalDateTime.now());
            screenDutyMessage.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            if (byId != null){
                screenDutyMessage.setRecVersion(byId.getRecVersion());
            }
            screenDutyMessageRepository.updateById(screenDutyMessage);
        }

        if (screenDutyMessage.getCustomId()!=null) {
            ScreenDutyMessage sumMessage=screenDutyMessageRepository.getOne(new LambdaQueryWrapper<ScreenDutyMessage>()
            .eq(ScreenDutyMessage::getOriginMsgId,screenDutyMessage.getCustomId()));
            ScreenMessage screenMessage=new ScreenMessage();
            screenMessage.setCustomCode(screenDutyMessage.getCustomId());
            screenMessage.setCustomName(screenDutyMessage.getCustomName());
            screenMessage.setMessage(screenDutyMessage.getTitle());
            if (!hzDeptInfo.getId().equals(screenDutyMessage.getCustomId())){
            BaseDeptInfo customDept = baseDeptInfoRepository.getById(screenDutyMessage.getCustomId());
            if (sumMessage==null) {
                sumMessage = new ScreenDutyMessage();
                BeanUtils.copyProperties(screenDutyMessage, sumMessage);
                sumMessage.setCustomId(hzDeptInfo.getId());
                sumMessage.setTitle("【"+customDept.getDeptName()+"】"+sumMessage.getTitle());
                sumMessage.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                sumMessage.setCreateTime(LocalDateTime.now());
                sumMessage.setUpdateTime(LocalDateTime.now());
                sumMessage.setId(null);
                sumMessage.setOriginMsgId(screenDutyMessage.getId());
                screenDutyMessageRepository.save(sumMessage);
            }else {
                String id=sumMessage.getId();
                BeanUtils.copyProperties(screenDutyMessage, sumMessage);
                sumMessage.setCustomId(hzDeptInfo.getId());
                sumMessage.setTitle("【"+customDept.getDeptName()+"】"+sumMessage.getTitle());
                sumMessage.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                sumMessage.setCreateTime(LocalDateTime.now());
                sumMessage.setUpdateTime(LocalDateTime.now());
                sumMessage.setId(id);
                sumMessage.setOriginMsgId(screenDutyMessage.getId());
                screenDutyMessageRepository.updateById(sumMessage);
                }
                WebSocketSendInfoDTO webSocketSendInfoDTO=new WebSocketSendInfoDTO();
                screenMessage.setModule("MESSAGE_DUTY_MESSAGE");
                webSocketSendInfoDTO.setMessage(sumMessage.getCustomName()+"报送1条值班信息，请及时查看！");
                webSocketSendInfoDTO.setScreenMessage(screenMessage);
                webSocketSendInfoDTO.setModule("MESSAGE_DUTY_MESSAGE");
                webSocketSendInfoServer.sendAllZS(webSocketSendInfoDTO);
            }
        }
        SecurityLog operateLog = new SecurityLog();
        operateLog.setCreateBy(screenDutyMessageSaveVO.getCreatePerson());
        operateLog.setCreateTime(LocalDateTime.now());
        operateLog.setIpAddress( IpUtils.getIpAddr(request));
        operateLog.setSDescription( JSON.toJSONString( screenDutyMessageSaveVO ) );
        operateLog.setSModule("ZBXXLS");
        operateLog.setSTitle("SBZG");
        securityLogService.save(operateLog);
        return BaseResult.ok(screenDutyMessage,"上报成功");
    }

    @Override
    public Object hide(ScreenMessageDistributeHideDTO screenMessageDistributeHideDTO) {
        ScreenDutyMessage screenMessageDistribute=repository.getById(screenMessageDistributeHideDTO.getId());
        screenMessageDistribute.setStatus(screenMessageDistributeHideDTO.getStatus());
        return repository.updateById(screenMessageDistribute);
    }

    @Override
    public void exportDocWithParam(String customName, String title, String mainBody, HttpServletResponse response) throws IOException, TemplateException {
        HashMap<String, Object> dataMap = new HashMap();

        String templatePath = systemConfig.getTemplatePath();
        dataMap.put("title", title);
        dataMap.put("content", mainBody+"");
        dataMap.put("time",LocalDateTime.now().getYear()+"年"
                +LocalDateTime.now().getMonth().getValue()+"月"
                +LocalDateTime.now().getDayOfMonth()+"日");
        String templateName = "国务院联防联控机制组督导工作类信息模板.ftl";
        response.setContentType("application/octet-stream;chartset=utf-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("值班信息.doc", "UTF-8"));
        WordUtils.generateWord(dataMap, templateName,templatePath,response);
    }

    @Override
    public void exportDocWithParam(JSONObject pararm, HttpServletResponse response) throws IOException, TemplateException {
        HashMap<String, Object> dataMap = new HashMap();
        String templatePath = systemConfig.getTemplatePath();
        dataMap.put("title", pararm.getString("title"));
        dataMap.put("customName", pararm.getString("customName"));
        dataMap.put("content",pararm.getString("mainBody"));
        dataMap.put("time",LocalDateTime.now().getYear()+"年"
                +LocalDateTime.now().getMonth().getValue()+"月"
                +LocalDateTime.now().getDayOfMonth()+"日");
        String templateName = "国务院联防联控机制组督导工作类信息模板.ftl";
        response.setContentType("application/octet-stream;chartset=utf-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("值班信息.doc", "UTF-8"));
        WordUtils.generateWord(dataMap, templateName,templatePath,response);
    }
}
